package com.xgry.bpm.api.base.login;

import com.xgry.bpm.api.business.author.service.TBAuthorService;
import com.xgry.bpm.common.utils.MiniUITreeCheckUtil;
import com.xgry.bpm.common.utils.Result;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
* @author Mr.Xing
* @version 创建时间：2018年7月1日 上午11:36:36
* 首页controller
*/
@RestController
@Slf4j
@RequestMapping("/index")
public class IndexController {

	@Autowired
	private TBAuthorService tbAuthorService;

    @ApiOperation(value = "根据角色id查询角色信息")
    @ApiImplicitParam(name = "pageIndex", value = "查询第几页", paramType = "query", required = true, dataType = "int")
    @PostMapping(value = "/index.do")
    public Result getAuthorTree(@RequestParam("roleIds")List<Integer> roleIds){
		List<MiniUITreeCheckUtil> miniUITreeCheckUtils = tbAuthorService.toAuthorTree(tbAuthorService.getAuthorDataByRoleIds(roleIds));
		return Result.success(miniUITreeCheckUtils);
    }

	/**
	 * 根据userId获取权限集合
	 * @param session
	 * @return
	@RequestMapping(value = "/index.do",produces = "application/json; charset=utf-8")
	@ResponseBody
	public String index(HttpSession session){
		try{
			UserInfo userInfo = (UserInfo) SecurityUtils.getSubject().getPrincipal();
				List<TreeVo> TreeList = new ArrayList<>();
				//JdbcTemplate jdbcTemplate = msFactory.getJdbcTemplate();
				List<UserInfoRole> userInfoRoles = userInfoRoleService.findByUserInfo(userInfo.getUserId());
				List<Integer> roleIds = userInfoRoles.stream().map(UserInfoRole::getRoleId).collect(Collectors.toList());

				List<RoleMath> listRoleMath = new ArrayList<>();
				List<RoleMath> roleMaths1 = roleMathService.findByRoleId1(list.toString().replace("[", "").replace("]", ""));
				listRoleMath.addAll(roleMaths1);

				for (RoleMath roleMath : listRoleMath) {
					Modular modular = modularService.findByModularId(roleMath.getModular().getModularId());
					if (modular.getModularState() == 1) {
						//放入模块
						if (roleMath.getMenus() == null || roleMath.getMenus().equals("")) {
							TreeVo modularTree = new TreeVo();
							modularTree.setId("modular" + roleMath.getModular().getModularId());
							modularTree.setText(roleMath.getModular().getModularName());
							modularTree.setPk(roleMath.getModular().getModularId());
							modularTree.setIconCls(roleMath.getModular().getModularLcons());
							//添加模块排序字段
							modularTree.setOrder(modular.getModularOrderId());
							//System.out.println("123"+modular.getModularOrderId());
							modularTree.setPid("");

							TreeList.add(modularTree);
						} else {
							//Modular modular1 = modularService.findByModularId(roleMath.getModular().getModularId());
							//放入菜单menu
							TreeVo MenuTree = new TreeVo();
							MenuTree.setId("menuId" + roleMath.getMenus().getMenuId());
							if (roleMath.getMenus().getParId() == 0) {
								MenuTree.setPid("modular" + roleMath.getModular().getModularId());
							} else {
								MenuTree.setPid("menuId" + roleMath.getMenus().getParId());
							}
							MenuTree.setPk(roleMath.getMenus().getMenuId());
							MenuTree.setText(roleMath.getMenus().getMenuName());
							MenuTree.setUrl(roleMath.getMenus().getMenuUrl());
							MenuTree.setIconCls(roleMath.getMenus().getMenuLcon());
							MenuTree.setFormListId(roleMath.getMenus().getFormMenuId());
							MenuTree.setFormName(roleMath.getMenus().getMenuName());
							MenuTree.setMenusFormTypes(roleMath.getMenus().getMenusFormTypes());
							//添加菜单排序字段
							//MenuTree.setMenusorder(modular.getModularId());
							MenuTree.setMenusorder(roleMath.getMenus().getMenuOrderId());
							//			System.out.println("====="+modular.getModularId());
							TreeList.add(MenuTree);
						}
					}
				}
			}
				List<TreeVo> TreeVolist = listToTree(TreeList);
				session.setAttribute(Const.SESSION_TREE_DATE, TreeVolist);
				UserInfo userInfo3 = (UserInfo) session.getAttribute(Const.SESSION_USER);
				json.put("treeDate", TreeVolist);
				json.put("userInfo", userInfo3);
				json.put("message", "返回用户");
		}catch (Exception e) {
			json.put("state","error");
			json.put("message", "系统异常，请检查系统日志");
			logger.error(e.getMessage());
		}
		return json.toString();
	} */

	/**
	 * 排序，根据模块排序字段排序
	public Comparator<TreeVo> order(){
		Comparator<TreeVo> comparator = new Comparator<TreeVo>() {
			@Override
			public int compare(TreeVo o1, TreeVo o2) {
				if (o1.getOrder() != o2.getOrder()) {
					return o1.getOrder()-o2.getOrder();
				}
				return 0;
			}
		};
		return comparator;
	}
     */
	/**
	 * 根据菜单排序字段进行排序


	public Comparator<TreeVo> menusorder(){
		Comparator<TreeVo> comparator = new Comparator<TreeVo>() {
			@Override
			public int compare(TreeVo o1, TreeVo o2) {
				if (o1.getMenusorder() != o2.getMenusorder()) {
					return o1.getMenusorder()-o2.getMenusorder();
				}
				return 0;
			}
		};
		return comparator;
	}

	//排序规则
	public List<TreeVo> listToTree(List<TreeVo> list){
	//	System.out.println("进入转换treelist方法");
		//模块排序
		List<TreeVo> listTree = new ArrayList<>();
		//System.out.println("list"+list);
		for(TreeVo tree:list) {
			if(tree.getPid() == "") {//pid为空为模块
				listTree.add(tree);
			}
			Collections.sort(listTree,order());
			//菜单排序
			List<TreeVo> childList = new ArrayList<>();

			//现在的
			for (TreeVo treeVo : list) {
				List<TreeVo> treeVoList = getChiId(treeVo.getId(), list);
				treeVo.setChildren(treeVoList);
			}
		}
		//System.out.println("跳出treelist方法");
		return listTree;
	}*/

	/**
	 * 获取子菜单进行递归排序

	public List<TreeVo> getChiId(String pid, List<TreeVo> allMenu) {
		//菜单
			ArrayList<TreeVo> voArrayList = new ArrayList<>();
		//遍历所有节点，将所有菜单的父id与模块的id进行比较
		for (TreeVo treeVo : allMenu) {
			//相等说明：为该模块下的子菜单
			if (treeVo.getPid().equals(pid)) {
				voArrayList.add(treeVo);
			}
		}
		//递归
		for (TreeVo treeVo : voArrayList) {
			treeVo.setChildren(getChiId(treeVo.getId(), allMenu));
		}
		//排序
		Collections.sort(voArrayList,menusorder());
		//如果节点下没有字节点，返回一个空的list（退出递归）
		if (voArrayList.size() == 0) {
			return new ArrayList<TreeVo>();
		}
		return voArrayList;
	}
     */


	/**
	 * 根据userId获取权限集合
	 * @param session
	 * @return

	@RequestMapping(value = "/indextest.do",produces = "application/json; charset=utf-8")
	@ResponseBody
	public String indextest(HttpSession session){
		try{
		//	System.out.println("sessionId"+session.getId());
			//UserInfo userInfo = (UserInfo)session.getAttribute(Const.SESSION_USER);
//			System.out.println("进入index.do方法");
	//		System.out.println("获取用户信息"+session.getAttribute(Const.SESSION_USER));
			//System.out.println("获取的用户信息为"+userInfo);
			UserInfo userInfo =userInfoService.findByUserInfoId(2);
	//		System.out.println(userInfo);
			if (userInfo == null) {
				json.put("message", "用户不存在！");
				json.put("status", "error");

			}else {
		//		System.out.println("查询出的userinfoid" + userInfo.getUserId());
				//UserInfo userInfo2 = userInfoService.findByUserInfoId(userInfo.getUserId());
				UserInfo userInfo2 = userInfoService.findByUserInfoId(2);
		//		System.out.println(userInfo2);
				List<RoleMath> listRoleMath = roleMathService.findByRoleId(userInfo2.getRole().getRoleId());
				List<TreeVo> TreeList = new ArrayList<>();


				for (RoleMath roleMath : listRoleMath) {
					//放入模块
					if (roleMath.getMenus() == null || roleMath.getMenus().equals("")) {
						TreeVo modularTree = new TreeVo();
						modularTree.setId("modular" + roleMath.getModular().getModularId());
						modularTree.setText(roleMath.getModular().getModularName());
						modularTree.setPk(roleMath.getModular().getModularId());
						modularTree.setIconCls(roleMath.getModular().getModularLcons());
						modularTree.setPid("");
						TreeList.add(modularTree);
					} else {
						//放入菜单menu
						TreeVo MenuTree = new TreeVo();
						MenuTree.setId("menuId" + roleMath.getMenus().getMenuId());
						if (roleMath.getMenus().getParId() == 0) {
							MenuTree.setPid("modular" + roleMath.getModular().getModularId());
						} else {
							MenuTree.setPid("menuId" + roleMath.getMenus().getParId());
						}
						MenuTree.setPk(roleMath.getMenus().getMenuId());
						MenuTree.setText(roleMath.getMenus().getMenuName());
						MenuTree.setUrl(roleMath.getMenus().getMenuUrl());
						MenuTree.setIconCls(roleMath.getMenus().getMenuLcon());
						TreeList.add(MenuTree);
					}
				}
				//TreeList.sort((x,y)->Integer.compare(x.getFormListId(),y.getFormListId()));
			//	System.out.println("aaaaa"+TreeList);
				List<TreeVo> TreeVolist = listToTree(TreeList);
				for (TreeVo treeVo : TreeVolist) {
			//		System.out.println("========"+treeVo);
				}
				session.setAttribute(Const.SESSION_TREE_DATE, TreeVolist);
		//		System.out.println("转换后的TreeList" + TreeVolist);
				json.put("treeDate", TreeVolist);
				json.put("message", "返回用户");
			//	System.out.println(json.toString());
				//json.put("date",userInfo.getRole().getRoleMaths());
			}
		}catch (Exception e){
			json.put("state","error");
			json.put("message", "系统异常，请检查系统日志");
			logger.error(e.getMessage());
		}
		return json.toString();
	}
	@RequestMapping(value = "/resCount.do",produces = "application/json; charset=utf-8")
	@ResponseBody
	public String resCount(HttpSession session) throws Exception {
		UserInfo userInfo = (UserInfo)session.getAttribute(Const.SESSION_USER);
		JSONObject json = new JSONObject();
		Integer userId = userInfo.getUserId();
		long dbCount = taskService.createTaskQuery().taskAssignee(userId+"").count();
		json.put("dbCount",dbCount);
		String countSql = "select count(*) from \r\n" +
				"(SELECT \r\n" +
				"fl.cTableName AS cTableName,\r\n" +
				"yb.bltime as createTime,\r\n" +
				"fl.formListId as formListId,\r\n" +
				"yb.taskId as id,\r\n" +
				"yb.actName as name,\r\n" +
				"yb.PROC_INST_ID_ as processId,\r\n" +
				"vb.TEXT_ as taskId\r\n" +
				"FROM [dbo].[V_TASKLIST_YB] yb\r\n" +
				"left join ACT_RU_VARIABLE vb\r\n" +
				"on yb.PROC_INST_ID_ = vb.PROC_INST_ID_ and vb.NAME_ = 'formtaskId'\r\n" +
				"left join form_list fl\r\n" +
				"on yb.ProcessDefinitionId = fl.processInstanceId\r\n" +
				"where\r\n" +
				"(yb.ASSIGNEE = '"+userId+"' OR yb.CANDIDATE = '"+userId+"')) t";
		JdbcTemplate jdbcTemplate = msFactory.getJdbcTemplate();
		List<Map<String, Object>> maps = jdbcTemplate.queryForList(countSql);
		JSONArray jsonArray = JSON.parseArray(JSON.toJSONString(maps));
		JSONObject jsonObject = jsonArray.getJSONObject(0);
		json.put("ybCount",jsonObject.get(""));
		String MsgCount = "select count(*) from socket_user where socketUser = " + userId;
		List<Map<String, Object>> maps1 = jdbcTemplate.queryForList(MsgCount);
		JSONArray jsonArray1 = JSON.parseArray(JSON.toJSONString(maps1));
		JSONObject jsonObject1 = jsonArray1.getJSONObject(0);
		json.put("MsgCount",jsonObject1.get(""));
		List<Map<String,Object>> tableNameList = sqlData.findTableName();
		JSONArray jsonArray2 = JSON.parseArray(JSON.toJSONString(tableNameList));
		int TaskCount = 0;
		JdbcTemplate jdbcTemplate1 = dbServer.getJdbcTemplate(2);
		for (int i=0;i<jsonArray2.size();i++){
			JSONObject jsonObject2 = jsonArray2.getJSONObject(i);
			String cTableName = jsonObject2.getString("cTableName");
			String countSql1 = "select count(*) from "+cTableName+" where "+cTableName+"_single_person_id ="+userId +" and "+cTableName+"_state in (1,2,3,4,5,6)";
			List<Map<String, Object>> list1 = jdbcTemplate1.queryForList(countSql1);
			JSONArray jsonArray3 = JSON.parseArray(JSON.toJSONString(list1));
			JSONObject jsonObject3 = jsonArray3.getJSONObject(0);
			Integer integer = jsonObject3.getInteger("");
			TaskCount+=integer;
		}
		json.put("TaskCount",TaskCount);
		return json.toString();
	}

	@RequestMapping(value = "/CountMsg.do",produces = "application/json; charset=utf-8")
	@ResponseBody
	public String msgNum(HttpSession session) throws Exception {
		JSONObject json  = new JSONObject();
		UserInfo userInfo = (UserInfo)session.getAttribute(Const.SESSION_USER);
		int msgNum = socketUserService.countMessage(userInfo.getUserId());
		json.put("msgNum", msgNum);
		return json.toString();
	}
     */
}




